import akshare as ak
from datetime import datetime
import pandas as pd
from mongo.MongoHelper import MongoHelper
from functools import wraps
from tools.log.logU import logU
from tools.conf.confU import confU
from tools.mail.mail import emailUtils

conf = confU().config
log = logU('').logger


def get_block_transactions(self, symbol, beg_date, end_date):
    log.debug(f'{symbol}{beg_date}{end_date} from get_block_transactions')
    try:
        coll = self.mongoHelper.mongo_db.get_collection(
            "blockTransactionDetail")
        result = ak.stock_dzjy_mrmx(
            symbol, start_date=beg_date, end_date=end_date)
        # ['序号', '交易日期', '证券代码', '证券简称', '涨跌幅', '收盘价', '成交价', '折溢率', '成交量', '成交额',
        #        '成交额/流通市值', '买方营业部', '卖方营业部']
        for num, row in enumerate(result.values.tolist()):
            # code + transactionDate 验重
            print(row)
            if not pd.isna(row[1]):
                date_string = row[1].strftime('%Y-%m-%d')
                datetime_obj = datetime.strptime(date_string, '%Y-%m-%d')
                q_con = {'code': row[2], 'transactionDate': datetime_obj}
                if_exist = coll.find_one(q_con)
                if not if_exist and len(row) == 13:
                    record = {
                        'seq': row[0],
                        'transactionDate': row[1].strftime('%Y-%m-%d'),
                        'code': row[2],
                        'shortName': row[3],
                        'upDownDegree': row[4],
                        'closingQuotation': row[5],
                        'bidQuotation': row[6],
                        'overflowRation': row[7],
                        'bidVolume': row[8],
                        'bidAmount': row[9],
                        'bidRatio': row[10],
                        'buyer': row[11],
                        'seller': row[12],
                        'createdTime': datetime.now(),
                        'source': 'AK'}
                    i = coll.insert_one(record)
                    if i is None:
                        log.error(
                            f"Error in  inserting record from get_block_transactions")
                    else:
                        log.info(
                            f"{i.inserted_id} inserted for get_block_transactions")
                else:
                    log.error(f"{row}长度有问题 ")
            else:
                log.error(f"{row} 日期有误无法入库")
    except Exception as e:
        log.error(f'from get_block_transaction error: {str(e)}')
    finally:
        print()


def get_daily_trading_data(
        self,
        code,
        market,
        beg_date,
        end_date,
        period='daily',
        adjust=''):
    log.info(f"{code},{market},{beg_date},{end_date}")
    try:
        data = ak.stock_zh_a_hist(
            symbol=code,
            period=period,
            start_date=beg_date,
            end_date=end_date,
            adjust=adjust
        )
        print(data.columns)
        vs = data.values.tolist()
        coll = self.mongoHelper.mongo_db.get_collection('equityHistory')
        for i, v in enumerate(vs):
            print(v)
            if not pd.isna(v[0]):
                re = coll.find_one({"code": code,
                                    'bizDate': v[0].strftime('%Y-%m-%d'),
                                    'rehabilitation': adjust})
                if not re:
                    record = {
                        'code': code,
                        'bizDate': v[0].strftime('%Y-%m-%d'),
                        'openingQuotation': v[1],
                        'closingQuotation': v[2],
                        'highestQuotation': v[3],
                        'lowestQuotation': v[4],
                        'volume': v[5],
                        'amount': v[6],
                        'vibration': v[7],
                        'updownPercent': v[8],
                        'updownAmount': v[9],
                        'turnoverRate': v[10],
                        'rehabilitation': adjust}
                    i = coll.insert_one(record)
                    log.info(i.inserted_id)
                else:
                    log.info(f'')
    except Exception as e:
        error_text = str(e)
        log.error(error_text + "")
    finally:
        log.debug("")


class AkshareDaily(object):

    def __init__(self, config):
        self.mongoHelper = MongoHelper(
            url=conf.get(
                'db', 'url'), database=conf.get(
                'db', 'database'))
        emailUtils(cfg=None)
        log.info("AkshareDaily initialized with mongodb database")


if __name__ == "__main__":

    get_daily_trading_data(
        self=AkshareDaily(
            config=None),
        code='600487',
        market='',
        beg_date='20240501',
        end_date='20240531',
        period='daily',
        adjust='qfq')
